package br.ita.battlefarm.views;

import br.ita.battlefarm.core.HumanSetupBuilder;
import br.ita.battlefarm.core.Position;
import br.ita.battlefarm.pieces.Piece;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;

public class SetupBuilderView extends View {

	private int mOffSet = 30;
	private HumanSetupBuilder setupBuilder;
	private OnTouchListener setupListener = new SetupTouchListener();
	private Paint white;
	private Paint red;
	
	public SetupBuilderView(Context context){
		super(context);
		initParams();
	}
	
	public SetupBuilderView(Context context, HumanSetupBuilder setupBuilder) {
		super(context);
		this.setupBuilder = setupBuilder;
		initParams();
	}
	
	private void initParams(){
		setOnTouchListener(setupListener);
		white = new Paint();
		white.setARGB(255, 255, 255, 255);
		red = new Paint();
		red.setARGB(255, 255, 0, 0);
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		drawNextPiece(canvas);	
	}

	private void drawNextPiece(Canvas canvas) {
		int mTileSize = 40;
		Piece piece = setupBuilder.getNextPiece();
		if( piece==null ){
			return;
		}
		piece.moveToOrigin();
		for( Position pos : piece.getPositions() ){
			if( pos.equals(piece.getBasePosition()) ){
				canvas.drawCircle(mOffSet + (pos.y+0.5f)*mTileSize, mOffSet + 
						(pos.x+0.5f)*mTileSize, 0.5f*mTileSize, red);
			}
			else{
				canvas.drawCircle(mOffSet + (pos.y+0.5f)*mTileSize, mOffSet + 
						(pos.x+0.5f)*mTileSize, 0.5f*mTileSize, white);
			}
		}
	}

	private class SetupTouchListener implements OnTouchListener{
		
		public boolean onTouch(View v, MotionEvent event) {
			switch(event.getAction()){
			case MotionEvent.ACTION_UP:
				setupBuilder.rotateNextPiece();
				invalidate();
				break;
			}
			return true;
		}
		
	}
}
